package com.ruoyi.wechat.service.impl;

import com.ruoyi.common.core.domain.model.WeChatUserInfo;
import com.ruoyi.common.properties.PlatformProperties;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.app.service.AppLoginService;
import com.ruoyi.wechat.service.WechatMpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description: 微信公众号接口实现类
 * date: 2023年04月17日 15:17
 * author: tmac-1
 * version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class WechatMpServiceImpl implements WechatMpService {
    private final WxMpService wxMpService;
    private final PlatformProperties platformProperties;
    private final AppLoginService appLoginService;

    @Override
    public String buildAuthorizationUrl() {
        return wxMpService.getOAuth2Service().buildAuthorizationUrl(platformProperties.getWeChatMp().getCallbackUrl(), WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
    }

    @Override
    public void callback() {
        HttpServletRequest request = ServletUtils.getRequest();
        HttpServletResponse response = ServletUtils.getResponse();
        String code = request.getParameter("code");
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            // 这里可以拿到：头像、昵称、openId、性别
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
            weChatUserInfo.setUserName(userInfo.getOpenid());
            weChatUserInfo.setNickName(userInfo.getNickname());
            weChatUserInfo.setAvatar(userInfo.getHeadImgUrl());
            weChatUserInfo.setSex(userInfo.getSex());
            weChatUserInfo.setOpenid(userInfo.getOpenid());
            weChatUserInfo.setUnionid(userInfo.getUnionId());
            String token = appLoginService.getToken(weChatUserInfo);
            response.sendRedirect(platformProperties.getWeChatMp().getLoginUrl() + "?token=" + token);
        } catch (WxErrorException e) {
            log.error("根据code获取AccessToken异常");
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
